import { ElMessage } from 'element-plus'
import storage from '@/utils/storage'
import axios from 'axios'
import { getCookieToken, getCookieLanguage, removeCookieToken } from '@/utils/cookie'
import { isBlob, isArrayBuffer } from "@/utils/is"

// const pathname: string = window.location.pathname.replace('/mtr', '')
const href = encodeURIComponent(window.location.href)
const workbench_rul: string = `${process.env.VUE_APP_LOGIN_URL}?callBack=${href}`

// 创建axios实例
const request = axios.create({
  baseURL: process.env.VUE_APP_SIM_API, // 所有的请求地址前缀部分
  timeout: 5000, // 请求超时时间(毫秒)
  withCredentials: true // 异步请求携带cookie
  // headers: {
  // 设置后端需要的传参类型
  // 'Content-Type': 'application/json',
  // 'token': x-auth-token',//一开始就要token
  // 'X-Requested-With': 'XMLHttpRequest',
  // },
})
// request拦截器
request.interceptors.request.use(
  config => {
    // 如果你要去localStor获取token,(如果你有)
    let token = getCookieToken()
    if (token) {
      // 添加请求头
      config.headers['authorization'] = token
    }
    config.headers['lang'] = getCookieLanguage() ?? 'zh_HK'
    return config
  },
  error => {
    // 对请求错误做些什么
    console.log('....error');
    
    return Promise.reject(error)
  }
)
// response 拦截器
request.interceptors.response.use(
  response => {
    const res = response.data
    // 如果是数据流, 自定义"数据流"返回格式
    const downloadFilename = response.headers["download-filename"] ?? ''
    if (isBlob(res)) {
      return {
        code: 200,
        data: res,
        isBlob: true,
        fileName: downloadFilename
      }
    }
    if (isArrayBuffer(res)) {
      return {
        code: 200,
        data: res,
        isArrayBuffer: true,
        fileName: downloadFilename
      }
    }
    // 对响应数据做点什么
    if (res.code != 200) {
      let user_tips_not_show = JSON.parse(storage.local.get('user_tips_not_show') ?? 'false')
      if (!user_tips_not_show) {
        ElMessage({
          message: res.msg || res.message,
          type: 'error',
          duration: 2 * 1000
        })
      }

      if (res.code === 1000007 || res.code === 1000008) {
        // 1000007=authorization不存在，请重新登录
        // 1000008=authorization已失效，请重新登录
        // to re-login
        // userStore.userLogout()
        storage.local.remove('user_info')
        storage.local.remove('authorization')
        removeCookieToken()
        location.href = workbench_rul
      }
    }
    return res
  },
  error => {
    // 对响应错误做点什么
    const { status, statusText } = error.response
    ElMessage({
      message: statusText || error?.message,
      type: 'error',
      duration: 2 * 1000
    })
    return Promise.resolve({ code: status, data: statusText })
  }
)
export default request
